package com.conph.moring.core;

import java.util.HashMap;
import java.util.Map;

public class ProxyBeanFactory {
	private static final Map<String, MecProxy> mecProxymap;//类名称对应的MecProxy对象
	private static final Map<String, String> beanNamemap;//别名信息
	
	static {
		mecProxymap = new HashMap<>();
		beanNamemap = new HashMap<>();
	};
	
	public <T> T getCGLProxy(Object object) {
		return CGLProxy(object.getClass(), object);
	}
	
	@SuppressWarnings("deprecation")
	public <T> T getCGLProxy(Class<?> klass) throws InstantiationException, IllegalAccessException {
		return CGLProxy(klass, klass.newInstance());
	}
	
	public void addBean(String beanName, String className) throws Exception {
		String orgClassName = beanNamemap.get(beanName);
		if(orgClassName != null) {
			throw new BeanNameAlreadyExistException();
		}
		
		beanNamemap.put(beanName, className);
		
	}
	
	@SuppressWarnings("unchecked")
	private <T> T CGLProxy(Class<?> klass, Object object) {
		String className = klass.getName();
		MecProxy mecProxy = mecProxymap.get(className);
		
		if(mecProxy != null) {
			return (T) mecProxy.getProxy();
		} else {//产生一系列的代理
			mecProxy = new MecProxy();
			T proxy = mecProxy.getCGLProxy(object);
			mecProxy.setProxy(proxy);
			mecProxymap.put(className, mecProxy);
			
			return proxy;
		}
	}
	
	public MecProxy getMecProxy(Class<?> klass) {
		MecProxy mecProxy = mecProxymap.get(klass.getName());
		
		if(mecProxy == null) {
			return null;
		}
		
		return mecProxy;
	}
	
	public <T> T getBeanProxy(String beanName) {
		String result = beanNamemap.get(beanName);
		
		if(result != null) {
			return mecProxymap.get(result).getProxy();
		}
		
		return null;
	}
	
	public <T> T getBeanProxy(Class<?> klass) {
		String className = klass.getName();
		MecProxy mecProxy = mecProxymap.get(className);
		
		if(mecProxy != null) {
			return mecProxy.getProxy();
		}
		
		return null;
	}
	
	public String getBeanClassName(String beanName) {
		return beanNamemap.get(beanName);
	}
}